package com.enjoy.springboot;

import com.enjoy.springboot.interfaces.WebServer;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import java.util.Map;

public class WhhSpringApplication {

    /**
     * 1.创建一个spring容器
     * 2.创建Tomcat对象
     * 3.生成DispatcherServlet对象，并且和前面创建出来的spring容器进行绑定
     * 4.将DispatcherServlet添加到Tomcat
     * 5.启动Tomcat
     *
     */
    public static ApplicationContext run(Class<?> clazz) {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(clazz);
        context.refresh();

        WebServer webServer = getWebServer(context);

        assert webServer != null;
        webServer.start(context);
        return context;
    }

    private static WebServer getWebServer(AnnotationConfigWebApplicationContext context) {
        Map<String, WebServer> webServerMap = context.getBeansOfType(WebServer.class);
        if (webServerMap.isEmpty()) {
            throw new NullPointerException();
        }
        if (webServerMap.size() > 1) {
            String type = Util.loadProperties("servlet.container.type");

            for (Map.Entry<String, WebServer> serverEntry : webServerMap.entrySet()) {
                assert type != null;
                if (serverEntry.getKey().contains(type)) {
                    return serverEntry.getValue();
                }
            }
        }

        return webServerMap.values().stream().findFirst().isPresent() ? webServerMap.values().stream().findFirst().get() : null;
    }

}
